/*
 * @Author: jiangxin
 * @Date: 2022-11-25 14:32:17
 * @Company: orientsec.com.cn
 * @Description:
 */
const webpack = require("webpack");
const { getDevConfig } = require("./utils/index");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const HtmlScriptPlugin = require("./utils/htmlscriptplugin");

const currentScript = process.env.npm_lifecycle_event;

// filename:业务名称
// env:开发[dev]/生产[prod]
// action:动作 serve/build
const {
  groups: { filename, env, action = "serve" }
} = currentScript?.match?.(
  /(?<filename>\w+-{1}\w+)-{1}(?<env>\w+)(:{1}(?<action>\w+))?/i
);

const getPlugins = () => {
  if (action === "build") {
    return [
      new webpack.DefinePlugin({
        INJECTWINDOW: `function(){
                    var currentenv=localStorage.getItem('SERVICEENV');
                    var SERVICEENV=currentenv?currentenv:${JSON.stringify(
                      process.env.SERVICE_ENV ?? "mock"
                    )};
                    console.log(SERVICEENV);
                    window.localStorage.setItem('SERVICEENV',SERVICEENV)
                    window.DEVCONFIG=${JSON.stringify(
                      getDevConfig(env, action)
                    )}
                }`
      }),
      new HtmlScriptPlugin()
    ];
  }

  if (action === "serve") {
    return [
      new webpack.DefinePlugin({
        INJECTWINDOW: `function(){
                var SERVICEENV=${JSON.stringify(
                  process.env.SERVICE_ENV ?? "mock"
                )}
                  console.log(SERVICEENV);
                  window.localStorage.setItem('SERVICEENV',SERVICEENV)
                  window.DEVCONFIG=${JSON.stringify(getDevConfig(env, action))}
    
            }`
      })
    ];
  }
};

module.exports = (env) => {
  const { WEBPACK_BUNDLE = false, WEBPACK_SERVE = false } = env;
  let devtool = "";
  let mode = "";
  if (WEBPACK_SERVE) {
    devtool = "cheap-module-source-map";
    mode = "development";
  }
  if (WEBPACK_BUNDLE) {
    devtool = "hidden-source-map";
    mode = "production";
  }
  return {
    mode,
    devtool,
    devServer: {
      open: `${filename}/index.html`,
      host: "0.0.0.0",
      devMiddleware: {
        publicPath: `/${filename}`
      }
    },
    plugins: [
      new HtmlWebpackPlugin({
        template: "index.html",
        inject: "body"
      }),
      ...getPlugins()
    ]
  };
};

